/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.pay;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.service.idgenerator.IdGeneratorServiceApi;
import com.lxk.service.pay.api.PayServiceApi;
import com.lxk.service.pay.enums.TradeTypeEnum;
import com.lxk.service.pay.param.PayRequestParam;
import com.lxk.service.pay.response.PayResultResponse;
import com.lxk.service.setting.api.SettingServiceApi;
import com.lxk.service.setting.response.ChannelWXPayDto;
import com.lxk.service.ums.response.UmsUserDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;

/**
 * 微信支付节点
 *
 * @author huahua
 * 2024/8/28
 */
@LiteflowComponent(value = FlowPayOrderNodeConst.WX_PAY)
@AllArgsConstructor
public class WxPayNode extends NodeComponent {
    private final PayServiceApi payServiceApi;
    private final IOmsOrderService omsOrderService;
    private final IdGeneratorServiceApi idGeneratorServiceApi;
    private final SettingServiceApi settingServiceApi;
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);

    @Override
    public void process() throws Exception {
        PayContext contextBean = getContextBean(PayContext.class);
        UmsUserDto user = contextBean.getUser();
        PayContext.PayInnerOrder payInnerOrder = contextBean.getPayInnerOrder();
        List<OmsOrderVo> omsOrder = contextBean.getOmsOrder();
        String tenantId = contextBean.getTenantId();
        PayRequestParam param = new PayRequestParam();
        List<ChannelWXPayDto> channelWXPay = settingServiceApi.wxPayConfigByTenantId(tenantId);
        if (CollUtil.isNotEmpty(channelWXPay)) {
            param.setAppId(channelWXPay.get(0).getAppId());
        }
        param.setUserId(user.getUserId());
        param.setWxOpenId(user.getWxAppOpenId());
        if (OrderEnums.PayType.WX_APP.getCode().equals(contextBean.getPayType())) {
            param.setPayType(TradeTypeEnum.WX_APP.getTradeType());
        } else if (OrderEnums.PayType.WX_JSAPI.getCode().equals(contextBean.getPayType())) {
            param.setPayType(TradeTypeEnum.WX_JSAPI.getTradeType());
            param.setWxOpenId(user.getWxMiniAppOpenId());
        } else if (OrderEnums.PayType.WX_MWEB.getCode().equals(contextBean.getPayType())) {
            param.setPayType(TradeTypeEnum.WX_MWEB.getTradeType());
            param.setWxOpenId(user.getWxMiniAppOpenId());
        }
        param.setTotalFee(payInnerOrder.getTotalPrice());
        param.setOutTradeNo(payInnerOrder.getOutTradeNo());
        param.setBody(StrUtil.format("微信支付订单" + payInnerOrder.getOutTradeNo()));
        if (StrUtil.isNotBlank(payInnerOrder.getCombineOutTradeNo())) {
            param.setAttach(payInnerOrder.getOutTradeNo() + "," + payInnerOrder.getCombineOutTradeNo());
        } else {
            param.setAttach(payInnerOrder.getOutTradeNo());
        }
        PayResultResponse response = payServiceApi.pay(param);
        if (!response.getSuccess()) {
            log.error("微信支付错误:{}", response.getMsg());
            throw new ServiceException(response.getMsg());
        }
        //设置微信支付返回对象
        PayContext.PayResult payResult = new PayContext.PayResult();
        payResult.setOmsOrder(omsOrder);
        payResult.setPackageParams(response.getPackageParams());
        payResult.setMsg(response.getMsg());
        payResult.setSuccess(response.getSuccess());
        contextBean.setPayResult(payResult);
    }

//    @Override
//    public void onSuccess() throws Exception {
//        PayContext contextBean = getContextBean(PayContext.class);
//        PayContext.PayResult payResult = contextBean.getPayResult();
//        if (payResult.getSuccess()) {
//            contextBean.getOmsOrder().forEach(omsOrderVo -> {
//                omsOrderService.setPayType(omsOrderVo.getId(), contextBean.getPayType(), contextBean.getPayInnerOrder().getOutTradeNo());
//            });
//        }
//    }


}
